import React from 'react';
import { browserHistory } from 'react-router'

import button from '../img/material/button.png'
import QRcode from '../img/result/left.gif'
import dashed from '../img/address/dashed.png'
import {ROOTURL,ROOTAPI} from '../../publicAPI/publicAPI.js'
require('../css/FacialmaskAddress.css');
class FacialmaskAddress extends React.Component {
	constructor(props) {
	    super(props);
	    this.state = {
	        name:"",
          phone:"",
          address:"",
          changeaddr:false,
          netPay:this.props.location.query.netPay
	    }
	}
	componentWillMount(){
       this.getUser()
	}
    componentDidMount(){
        
    }
    // 弹出遮罩层
    showCover(){
        document.getElementsByClassName('fm-address-cover')[0].style.display = 'block';
    }
    // 关闭遮罩层
    closeCover(){
        document.getElementsByClassName('fm-address-cover')[0].style.display = 'none';
    }
    //获取地址
    getUser(){
        var _this=this
        let {id}=JSON.parse(localStorage.getItem("customerInfo"));
        var url = ROOTAPI + 'kabuy/shipaddress/instance.api?id='+id;
        fetch(url, {
                method : 'get',
                credentials: 'include',
            }).then(res=>{
                if(res.ok){
                    res.json().then(data=>{
                        console.log( JSON.stringify(data));
                        _this.setState({
                            name:data.cname,
                            phone:data.cphone,
                            address:data.fullAddr,
                            changeaddr:true
                        })
                    })
                }
        })
    }
    //新增或修改地址
    clickSave(){
        // 表单检测
        let name = document.getElementById('input_name').value;
        let phone = document.getElementById('input_phone').value;
        let address = document.getElementById('input_address').value;
        if (name=='' || phone=='' || address=='') {
            name == '' ? name = '姓名' : name = '';
            phone == '' ? phone = '手机号码' : phone = '';
            if (name != '' && phone != '') {
                phone = '、' + phone;
            }
            address == '' ? address = '收货地址' : address = '';
            if ((phone != '' || name != '') && address != '') {
                address = '、' + address;
            }
            alert("亲，请填写" + name + phone + address + "哦，不然会快递哥哥会找不到您的！")
        }else {
            let {id}=JSON.parse(localStorage.getItem("customerInfo"));
            let url = ROOTAPI + 'kabuy/shipaddress/instance.api';
            
            this.state.changeaddr==true?
            fetch(url, {
                    method : 'POST',
                    credentials: 'include',
                    body:JSON.stringify({
                        id:id,
                        customerId:id,
                        cname:this.state.name,
                        cphone:this.state.phone,
                        fullAddr:this.state.address
                    })
                }).then(res=>{
                    if(res.ok){
                        res.json().then(data=>{
                            this.placeOrder()
                        })
                    }
            }):
            fetch(url, {
                method : 'POST',
                credentials: 'include',
                body:JSON.stringify({
                    customerId:id,
                    cname:this.state.name,
                    cphone:this.state.phone,
                    fullAddr:this.state.address
                })
            }).then(res=>{
                if(res.ok){
                    res.json().then(data=>{
                        this.placeOrder()
                    })
                }
            })
            }
  
    }
    namechange(e){
        const name = e.target.value
        this.setState({
            name: name
        })
    }
    phonechange(e){
        const phone = e.target.value
        this.setState({
            phone: phone
        })
    }
    addrchange(e){
        const address = e.target.value
        this.setState({
            address: address
        })
    }
    //使用微信支付
    placeOrder() {
       let {openid} = JSON.parse(localStorage.getItem('userInfo'))
       let id = this.props.location.query.id;
       let url = ROOTAPI+'kabuy/wxpay/pay.api?contractId='+id+'&payerId='+openid;
       if (id) {
              fetch(url, {
                    method : 'POST',
                    mode: 'cors',
                    credentials: 'include',
                    Cookie: document.cookie
                    }).then(res=>{
                        if(res.ok){
                            res.json().then(data=>{
                                this.weixinPay(id,data)
                            })
                       }else{
                          res.json().then(data=>{
                            
                          })                                   
                       }
            })

       }
       
    }
    weixinPay(id, data) {
        if (data.gbwcpr) {
          let u = navigator.userAgent;
          let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
          let {netPay} = this.state;
          sessionStorage.setItem('confirmCharge', JSON.stringify({             
              netPay: netPay,
              gbwcpr: data.gbwcpr,
              pathSuccess: {pathname: `/result`},
          }))
          if (isiOS) {
              location.href = `/confirmadd`
          } else {
              browserHistory.push({pathname:`/confirmadd`})
          }
      } else {
          // this.goFailPage();
      }

    }

    render() {
        return (
            <div className="fm-address">
                <div className="fm-address-cover">
                    <div className="fm-address-cover-button" onClick={this.closeCover.bind(this)}>
                        <img src={button}/>
                    </div>
                    <div className="fm-address-cover-QRcode">
                        <img src={QRcode}/>
                    </div>
                    <div className="fm-address-cover-word">
                        请长按二维码关注公众号<br/>进入公众号点击菜单进行购买！
                    </div>    
                </div>
                <div className="fm-address-table">
                    <div className="fm-address-table-title">
                        请填写收货地址
                    </div>
                    <div className="fm-address-table-name">
                        <div className="fm-address-table-name-word">真实姓名：</div>
                        <div className="fm-address-table-name-input"><input type="text" id="input_name" value={this.state.name} onChange={(e) => this.namechange(e)}/></div>
                        <div className="fm-address-table-name-dashed"><img src={dashed}/></div>
                    </div>
                    <div className="fm-address-table-phone">
                        <div className="fm-address-table-phone-word">手机号码：</div>
                        <div className="fm-address-table-phone-input"><input type="text" id="input_phone" value={this.state.phone} onChange={(e) => this.phonechange(e)}/></div>
                        <div className="fm-address-table-phone-dashed"><img src={dashed}/></div>
                    </div>
                    <div className="fm-address-table-address">
                        <div className="fm-address-table-address-word">收货地址：</div>
                        <div className="fm-address-table-address-input"><input type="text" id="input_address" placeholder="详细地址"  value={this.state.address} onChange={(e) => this.addrchange(e)}/></div>
                    </div>
                    <div className="fm-address-table-att">
                        <div className="fm-address-table-att-word1">* 关注公众号后购买可以储存收货地址哦！</div>
                        <div className="fm-address-table-att-word2" onClick={this.showCover.bind(this)}>点击这里关注</div>
                    </div>
                </div>
                <div className="fm-address-button-save" onClick={this.clickSave.bind(this)}>
                    确定
                </div>
            </div>
        )
    }
}


export default FacialmaskAddress;